import { compile } from "ass-compiler";
import { Lrc, Lyric } from "lrc-kit";
import { LyricChar } from "./type";
export function compileASS(text: string, options?: object) {
  try {
    return compile(text, options || {});
  } catch (error) {
    return null;
  }
}

export function getDialogue(text: string) {
  const compile = compileASS(text);
  if (!compile) {
    return null;
  }
  const dialogues = compile.dialogues;
  if (!dialogues) {
    return null;
  }

  return dialogues;
}

export function parseAss(text: string): LyricChar[][] {
  const dialogue = getDialogue(text);

  const lyrics: LyricChar[][] = [];
  dialogue?.map((dialogue) => {
    const { start, end, slices } = dialogue;

    let chartStart = start;
    const lyricLine: LyricChar[] = [];
    slices.forEach((slice) => {
      const { fragments } = slice;
      fragments.forEach((fragment) => {
        const { tag, text } = fragment;
        lyricLine.push({
          start: chartStart,
          end: (chartStart += (tag?.kf || 0) / 100),
          text,
        });
      });
    });
    lyrics.push(lyricLine);
  });

  return lyrics;
}

export function parseLrc(text: string): Lrc | null {
  try {
    const lrc = Lrc.parse(text);
    const a = [...lrc.lyrics];
    a.sort((a, b) => a.timestamp - b.timestamp);
    lrc.lyrics = a;
    return lrc;
  } catch (error) {
    return null;
  }
}

/**
 * 解析ASS文件为LRC格式
 * @param text ASS文件内容
 * @returns LRC格式字符串
 */
export function parseAss2Lrc(text: string) {
  const dialogues = getDialogue(text);
  if (!dialogues) {
    return null;
  }
  const lrc = new Lrc();
  dialogues.forEach((dialogue) => {
    const { start, slices } = dialogue;
    const text = slices
      .map((slice) => {
        const { fragments } = slice;
        return fragments.map(({ text }) => text).join("");
      })
      .join("");
    lrc.lyrics.push({
      content: text,
      timestamp: start,
    });
  });
  return lrc.toString();
}

/**
 * 时间戳转 00:00:00.00 格式
 * @param timestamp 时间戳
 * @returns 00:00:00.00 格式字符串
 */
export function timestampToTimeString(timestamp: number) {
  const hours = Math.floor(timestamp / 3600);
  const minutes = Math.floor((timestamp % 3600) / 60);
  const seconds = Math.floor(timestamp % 60);
  const milliseconds = Math.floor((timestamp % 1) * 100);
  return `${hours.toString().padStart(2, "0")}:${minutes.toString().padStart(2, "0")}:${seconds
    .toString()
    .padStart(2, "0")}.${milliseconds.toString().padStart(2, "0")}`;
}

export function isLyricCharsType(lyricLine: any): lyricLine is LyricChar[] {
  if (Array.isArray(lyricLine)) {
    return true;
  }
  return false;
}

export function isLyricType(lyricLine: any): lyricLine is Lyric {
  if (lyricLine?.timestamp !== undefined && lyricLine?.content !== undefined) {
    return true;
  }
  return false;
}
